<template>
	<view class="order-wp">
		<!-- 商品详情 -->
		<goodsInfo :goodsInfo="goodsInfo" :canToDetail="formQrCode" :openId="goodsOwnerOpenId"></goodsInfo>
		<!-- 数量选择 -->
		<view class="card flex_between_center">
			<view class="title1">
				数量
			</view>
			<view class="">
				<u-number-box :min="1" :max="100" :step="1" v-model="number">
					<view slot="minus" class="minus">
						<u-icon name="minus" size="25"></u-icon>
					</view>
					<text slot="input" class="input">{{number}}</text>
					<view slot="plus" class="minus">
						<u-icon name="plus" size="25"></u-icon>
					</view>
				</u-number-box>
			</view>
		</view>
		<!-- 联系人 -->
		<view class="card">
			<u-button style="width: 500rpx;" @click="handleHistory">选择历史订单回填信息</u-button>

			<u--form errorType="message" labelWidth="auto" labelPosition="top" :model="model" :rules="rules" ref="formRef"
				:borderBottom="false" :labelStyle="{fontSize:'28rpx',color:'#1D2129',margin:'5rpx 0'}">
				<u-form-item label="收货人" prop="takePeople" required>
					<u--input maxlength="10" placeholderStyle="background:#f7f8fa;color:#C9CDD4"
						:custom-style="{padding:'10rpx 20rpx',lineHeight:'74rpx',fontSize:'28rpx',backgroundColor:'#F7F8FA',height:'74rpx'}"
						v-model="model.takePeople" border="none" placeholder="请填写收货人"></u--input>
				</u-form-item>
				<u-form-item label="收货地址" prop="address" required>
					<u-input maxlength="30" placeholderStyle="background:#f7f8fa;color:#C9CDD4"
						:custom-style="{padding:'10rpx 20rpx',lineHeight:'74rpx',fontSize:'28rpx',backgroundColor:'#F7F8FA',height:'74rpx'}"
						v-model="model.address" border="none" placeholder="请填写收货地址">
						<template slot="suffix">
							<u-button type="primary" text="选择位置" @click="getLocation"></u-button>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item label="联系电话" prop="mobile" required>
					<u--input maxlength="11" placeholderStyle="background:#f7f8fa;color:#C9CDD4"
						:custom-style="{padding:'10rpx 20rpx',lineHeight:'74rpx',fontSize:'28rpx',backgroundColor:'#F7F8FA',height:'74rpx'}"
						v-model="model.mobile" border="none" placeholder="请填写联系电话"></u--input>
				</u-form-item>
				<u-form-item label="配送时间" prop="deliveryTime">
					<view @click="handleDeliveryTimeSelect">
						<u-input placeholderStyle="background:#f7f8fa;color:#C9CDD4"
							:custom-style="{padding:'10rpx 20rpx',lineHeight:'74rpx',fontSize:'28rpx',backgroundColor:'#F7F8FA',height:'74rpx'}"
							v-model="model.deliveryTime" border="none" placeholder="请选择配送时间" readonly></u-input>
					</view>
				</u-form-item>
				<u-form-item label="留言" prop="remark">
					<u-textarea maxlength="30" placeholderStyle="background:#f7f8fa;color:#C9CDD4"
						:custom-style="{fontSize:'28rpx',backgroundColor:'#F7F8FA'}" v-model="model.remark" border="none"
						placeholder="请填写留言" autoHeight :maxlength="140"></u-textarea>
				</u-form-item>
				<view class="info-title1">
					*收货信息会发送至商家，由商家自行配送
				</view>
			</u--form>

		</view>
		<view class="pay-wp" v-if="goodsInfo.onlinePay">
			<view class="pay-main" :style="{paddingBottom:showCoupon?'':'20rpx'}">
				<u-radio-group :borderBottom="true" iconPlacement="right" size="30" placement="column" v-model="payInfo.type">
					<view class="pay-item" v-if="payInfo.weChat">
						<u-radio iconSize="28" :name="2">
							<view class="pay-label flex-1">
								微信支付
							</view>
							<image src="https://file.casugn.com/storecompcard/temp/weixin_1704935744098.png" class="pay-img"
								@click="handlePayChange(2)">
							</image>

						</u-radio>
					</view>
					<view class="pay-item" v-if="payInfo.aliPay">
						<u-radio iconSize="28" :name="1">
							<view class="pay-label flex-1">
								支付宝支付
							</view>
							<image src="https://file.casugn.com/storecompcard/temp/zhifubao_1704935727424.png" class="pay-img"
								@click="handlePayChange(1)">
							</image>

						</u-radio>
					</view>

					<view class="pay-item" v-if="payInfo.rests">
						<u-radio iconSize="28" :name="3">
							<view class="pay-label flex-1">
								其他支付
							</view>
							<image src="https://file.casugn.com/storecompcard/temp/qita_1704935757198.png" class="pay-img"
								@click="handlePayChange(3)">
							</image>
						</u-radio>
					</view>
				</u-radio-group>
				<view class="coupon-item" @click="goToChooseCoupon" v-if="showCoupon && goodsInfo.voucher==1">
					<view class="left flex-1 flex_start_center" style="flex: 1;">
						<image src="https://file.casugn.com/storecompcard/temp/quan_1704943148990.png" mode=""
							style="width: 40rpx;height: 40rpx;"></image>
						<view class="flex-1" style="margin-left: 20rpx;">
							选择代金券
						</view>
					</view>
					<view class="right flex_start_center">
						<view class="count" v-if="voucher.price>0">
							-￥{{voucher.price}}
						</view>
						<image src="https://file.casugn.com/storecompcard/temp/direction／right_1704936247334.png" mode=""
							style="height: 40rpx;width: 40rpx;"></image>
					</view>

				</view>
			</view>
		</view>
		<!-- 提交 -->
		<view class="bottom-box">
			<view class="submit-wp">
				<view style="font-size: 28rpx;color: #86909C;">
					共{{number}}件
				</view>
				<template v-if="goodsInfo.price||goodsInfo.price===0">
					<view style="height: 40rpx;font-size: 28rpx;">
						,合计：
					</view>
					<view class="totalPrice u-line-1">
						￥ {{totalPrice}}
					</view>
				</template>
				<u-button @click="showOrderPop" :custom-style="{
			  background:'#276aee',
			  borderRadius:'168rpx',
			  color: '#fff',
			  width: '192rpx',
			  border:'none'
			}">提交订单</u-button>
			</view>
		</view>
		<!-- 弹窗 -->
		<u-popup :show="showPopup" mode="center" :safeAreaInsetBottom="false">
			<view class="popup-wp">
				<view class="title">
					{{payInfo.type==1?'支付宝支付':payInfo.type==2?'微信支付':'其他方式支付'}}
				</view>
				<view class="title2" v-if="payInfo.type==1 ||payInfo.type==2">
					本平台不涉及资金往来,请扫商家收款码进行支付
				</view>
				<view class="qrcode flex_center">
					<image v-if="payInfo.type==1 " :src="payInfo.aliPay" mode="" show-menu-by-longpress
						style="height: 240rpx;width: 240rpx;">
					</image>
					<image v-if="payInfo.type==2" :src="payInfo.weChat" mode="" show-menu-by-longpress
						style="height: 240rpx;width: 240rpx;">
					</image>
					<textarea disabled v-model='payInfo.rests' :height="90" v-if="payInfo.type==3"
						style="background:#fff;width: 100%;height: 180rpx;" />
				</view>

				<view class="screenshot">
					<view class="screenshot-title">支付截图</view>
					<view>
						<view class="flex_center" @click="choosePicImg">
							<view v-if="model.payProof">
								<u-image :src="model.payProof" width="218rpx" height="218rpx" mode="widthFix"></u-image>
							</view>
							<view v-else class="uploadWp">
								<u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
								<text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
							</view>
						</view>
					</view>
				</view>

				<view class="title3">
					<view class="btn1" @click="closePop">
						取消支付
					</view>
					<view class="btn2" @click="submitOrder">
						完成支付
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 历史订单 -->
		<HistoryOrdersModal ref="historyOrdersModal" @confirm="historyOrderConfirm"></HistoryOrdersModal>
		<!-- 配送时间选择器 -->
		<cus-delivery-time ref="deliveryTimeModal" @confirm="deliveryTimeConfirm"></cus-delivery-time>
	</view>
</template>

<script>
	import goodsInfo from '@/pagesMall/components/goodsInfo/goodsInfo.vue'
	import HistoryOrdersModal from './components/HistoryOrdersModal.vue'
	import baseConfig from '@/config/baseUrl.js'
	const chooseLocation = requirePlugin('chooseLocation');

	import {
		mapGetters
	} from 'vuex'
	export default {
		components: {
			goodsInfo,
			HistoryOrdersModal
		},
		data() {
			return {
				number: 1,
				goodsId: '',
				goodsInfo: {},
				orderInfo: {},
				model: {
					takePeople: '',
					address: '',
					coord: '',
					mobile: '',
					remark: '',
					payProof: '',
					deliveryTime: '',
				},

				payType: {},
				couponCount: 0,
				showPopup: false,
				rules: {
					takePeople: [{
						required: true,
						message: '请输入收货人',
						trigger: ['blur', 'change']
					}],
					address: [{
						required: true,
						message: '请输入收货地址',
						trigger: ['blur', 'change']
					}],
					mobile: [{
						required: true,
						message: '请输入联系电话',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}]
				},
				showCoupon: false,
				payInfo: {},
				goodsOwnerOpenId: '',
				voucher: {
					price: 0
				},
				formQrCode: false,
				onloadOptionStr: '',

			};
		},
		onLoad(opt) {
			console.log(opt);
			this.onloadOptionStr = JSON.stringify(opt || {})
			let data = uni.getStorageSync('openId')
			if (opt.scene) {
				this.formQrCode = true
				if (data.openid) {
					this.getGoodsInfoForCode(opt.scene, data.openid)
				} else {
					uni.login({
						provider: 'weixin',
						onlyAuthorize: true,
						success: async (loginRes) => {
							let code = loginRes.code
							let payload = {
								code
							}
							let res = await this.$api.getOpenIdByCode(payload);
							if (res) {
								this.openId = res.openid
								this.unionId = res.unionid
								this.getGoodsInfoForCode(opt.scene, res.openid)
								this.$store.commit('setOpenId', res)
							} else {
								uni.showToast({
									title: '获取数据失败,请检查网络',
									icon: 'none'
								});
							}
						}
					});
				}
			}

			if (opt.goodsId) {
				this.goodsId = opt.goodsId
				this.goodsOwnerOpenId = opt.openId
				this.showCoupon = opt.hiddenBuyBtn == 1 ? false : true
				this.getGoodsInfo()
				this.getPayInfo()
			}
		},
		onShow() {
			//地图插件选点
			const location = chooseLocation.getLocation();
			if (location != null) {
				// console.log('获取地址信息', location);
				this.model.address = location.address
				this.model.coord = JSON.stringify(location) //发送给后台字符串
			}
		},
		onReady() {
			this.$refs.formRef.setRules(this.rules)
		},
		onUnload() {
			// 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
			chooseLocation.setLocation(null);
		},
		computed: {
			...mapGetters(['userInfo']),
			totalPrice() {
				let val = this.number * this.goodsInfo.price - this.voucher.price
				if (val && val > 0) {
					let value = Math.round(parseFloat(val) * 100) / 100;
					let valMoney = value.toString().split(".");
					if (valMoney.length == 1) {
						value = value.toString() + ".00";
						return value;
					}
					if (valMoney.length > 1) {
						if (valMoney[1].length < 2) {
							value = value.toString() + "0";
						}
						return value;
					}
					return value;
				} else {
					return "0.00";
				}
			}
		},

		methods: {
			handleDeliveryTimeSelect() {
				this.$refs.deliveryTimeModal.open(this.model.deliveryTime)
			},
			handleHistory() {
				this.$refs.historyOrdersModal.open()
			},
			historyOrderConfirm(item) {
				this.model.takePeople = item.takePeople
				this.model.address = item.address
				this.model.mobile = item.mobile
				this.model.coord = item.coord
			},
			deliveryTimeConfirm(value) {
				this.model.deliveryTime = value
			},
			getLocation() {
				const key = baseConfig.mapData.mapKey; //使用在腾讯位置服务申请的key
				const referer = baseConfig.mapData.appName //调用插件的app的名称
				let location = ''
				if (this.model.coord) {
					let tLocation = JSON.parse(this.model.coord)
					location = JSON.stringify({
						latitude: tLocation.latitude,
						longitude: tLocation.longitude
					});
				}

				this.getPermission('scope.userLocation', () => {
					uni.navigateTo({
						url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`
					});
				})
			},
			getPermission(scope, callback) {
				// 读取 小程序已经授权的权限
				uni.getSetting({
					success(res) {
						console.log(res);
						// 判断是否拥有此权限进行拉起授权  和 重新授权功能
						if (!res.authSetting[scope]) {
							uni.authorize({
								scope: scope,
								success() {
									callback()
								},
								fail(err) {
									uni.showModal({
										title: '检测到您已拒绝位置授权，是否重新授权',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success() {
														console.log('开启权限成功');
													},
													fail() {
														console.log('开启权限失败');
													}
												});
											} else if (res.cancel) {
												console.log('拒绝开启开启权限');
											}
										}
									});
								}
							})
						} else {
							callback()
						}
					}
				})
			},
			choosePicImg() {
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					success: async (rst) => {
						let tPath = rst.tempFiles[0].tempFilePath
						this.model.payProof = await this.uploadFilePromise(tPath)
					}
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
			async getGoodsInfoForCode(id, openid) {
				let res = await this.$api.getProdShopDetail({
					id: id,
					openId: openid
				})
				if (res.success) {
					this.goodsInfo = res.result
					this.goodsId = res.result.id
					this.goodsOwnerOpenId = res.result.openId

					if (this.goodsInfo.onlinePay) {
						this.getPayInfo()
					}
				} else {
					this.goodsInfo = {}
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			},
			closePop() {
				this.showPopup = false
			},
			showOrderPop() {
				if (this.goodsInfo.onlinePay) {
					if (!this.payInfo.type) {
						uni.showToast({
							icon: 'none',
							title: '请选择支付方式'
						})
						return
					}
					// this.$refs.formRef.clearValidate()
					this.$refs.formRef.validate().then(async res => {
						this.showPopup = true
					})
				} else {
					this.$refs.formRef.validate().then(async res => {
						this.submitOrder()
					})
				}

			},
			handlePayChange(index) {
				this.payInfo.type = index
			},
			async getPayInfo() {
				let {
					success,
					code,
					result
				} = await this.$api.getPayInfo({
					openId: this.goodsOwnerOpenId
				})
				if (code == 200 && success) {
					this.payInfo = result
				}
			},
			async submitOrder() {
				console.log('submitOrder');
				let {
					openid
				} = uni.getStorageSync('openId')
				let payable = Number(this.totalPrice)
				let payload = {
					...this.goodsInfo,
					...this.model,
					give: 0,
					payable,
					purchaseOpenId: openid,
					shopOpenId: this.goodsOwnerOpenId,
					shopType: this.goodsInfo.voucher,
					prodId: this.goodsInfo.id,
					num: this.number,
					voucher: this.voucher.price > 0 ? 1 : 0,
					voucherCodeId: this.voucher.id ? this.voucher.id : '',
					voucherPrice: this.voucher.price ? this.voucher.price : '',
					id: '',
					createTime: '',
				}
				console.log(payload);
				let {
					success,
					code,
					result,
					message
				} = await this.$api.addShopOrder(payload)
				if (code == 200 && success) {
					this.showPopup = false
					// uni.showToast({
					// 	icon: 'none',
					// 	title: message
					// })
					// setTimeout(() => {
					// 	let pages = getCurrentPages()
					// 	if (pages.length > 1) {
					// 		uni.navigateBack()
					// 	} else {
					// 		uni.reLaunch({
					// 			url: '/pages/card/card'
					// 		})
					// 	}
					// }, 1000)
					uni.redirectTo({
						url: `/pagesMall/mallCenter/orderSuccess?lastPageOptionStr=${this.onloadOptionStr}`
					})

				} else {
					uni.showToast({
						icon: 'none',
						title: message
					})
				}
			},
			goToChooseCoupon() {
				uni.navigateTo({
					url: '/pagesMall/coupon/myCoupon'
				})
			},
			// handleChange({
			// 	name
			// }) {
			// 	this.payType = name
			// 	let item = this.payTypeList.find(item => item.name == this.payType)
			// 	console.log(item);
			// },
			async getGoodsInfo() {
				let res = await this.$api.getProdShopDetail({
					id: this.goodsId,
					openId: this.goodsOwnerOpenId
				})
				if (res.success) {
					this.goodsInfo = res.result
				} else {
					this.goodsInfo = {}
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.order-wp {
		padding-top: 32rpx;
		background-color: #E5E6EB;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);

		.info-title1 {
			width: 482rpx;
			height: 36rpx;
			font-size: 26rpx;
			font-weight: 400;
			color: #C9CDD4;
			line-height: 36rpx;
		}

		.submit-wp {
			margin: 16rpx 32rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			.totalPrice {
				height: 50rpx;
				font-size: 36rpx;
				font-weight: 500;
				color: #FF3131;
				line-height: 50rpx;
				margin: 0 20rpx;

			}


		}

		.pay-wp {
			border-radius: 16rpx;
			margin: 32rpx;

			background-color: #fff;

			.pay-main {
				.coupon-item {
					padding: 0 32rpx;
					height: 108rpx;
					display: flex;
					align-items: center;
				}

				.pay-item {

					padding: 17rpx 32rpx 0 32rpx;
					height: 108rpx;
					display: flex;

					.count {
						margin-right: 20rpx;
						height: 40rpx;
						font-size: 30rpx;
						font-weight: 600;
						color: #FF3131;
						line-height: 39rpx;

					}

					.pay-img {
						width: 40rpx;
						height: 40rpx;
					}

					.pay-label {
						width: 518rpx;
						margin: 0 20rpx;
						height: 44rpx;
						font-size: 32rpx;
						font-weight: 400;
						color: #1D2129;
						line-height: 44rpx;

					}
				}

				.chooseCoupon {
					padding: 0 32rpx;
					height: 108rpx
				}
			}
		}
	}

	.title1 {
		width: 64rpx;
		height: 44rpx;
		font-size: 32rpx;
		font-weight: 400;
		color: #1D2129;
		line-height: 44rpx;

	}

	.card {
		margin: 24rpx 32rpx;
		padding: 24rpx;
		border-radius: 16rpx;
		background-color: #fff;
	}

	.popup-wp {
		padding: 50rpx;

		.title {
			height: 48rpx;
			font-size: 34rpx;
			font-weight: 400;
			color: #1D2129;
			line-height: 40rpx;
		}

		.qrcode {
			margin-top: 40rpx;
		}

		.title2 {
			margin-top: 24rpx;
			width: 464rpx;
			height: 84rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #86909C;
			line-height: 42rpx;

		}

		.screenshot {
			margin-top: 40rpx;

			.screenshot-title {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				font-weight: 400;
				color: #86909C;
				line-height: 1.5;
			}
		}

		.title3 {
			margin-top: 40rpx;
			display: flex;
			justify-content: flex-end;

			.btn1 {
				width: 120rpx;
				height: 42rpx;
				font-size: 30rpx;
				color: #86909C;
				line-height: 35rpx;

			}

			.btn2 {
				margin-left: 56rpx;
				width: 120rpx;
				height: 42rpx;
				font-size: 30rpx;
				color: #1A74FF;
				line-height: 35rpx;

			}
		}
	}

	.uploadWp {
		width: 218rpx;
		height: 218rpx;
		background-color: #f7f8fa;
		justify-content: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
	}
</style>
<style lang="scss">
	// page {
	// 	height: 100%;
	// 	background-color: #E5E6EB;
	// }

	.minus {
		width: 56rpx;
		height: 56rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f7f8fa;
		color: #000;
	}

	.input {
		padding: 0 30rpx;
		color: #000;
	}
</style>